import { TreeSelect } from 'antd';
import { AxFormItemBase } from '../lib/AxFormItemBase';
import { AxLabel } from '@/components/AxBase';
import { axhelper } from '@/shared/axhelper';

const valueMap = {};
const loops = (list, parent) => {
  return (list || []).map(({ children, value, title }) => {
    const node = (valueMap[value] = {
      parent,
      value,
      title,
    });
    node.children = loops(children, node);
    return node;
  });
}
/**
 * 
 * @param {string} key 键
 * @param {string} prop  值的属性（value,title） 
 */
const getFullPath = (key, prop) => {
  const path = [];
  let current = valueMap[key];
  while (current) {
    path.push(current[prop]);
    current = current.parent;
  }
  return path.reverse().join('');
}
/**
 * 自定义搜索下拉框
 * @param label 标签
 * @param field 字段名称
 * @param value 值
 * @param data 选项数据 [{ value: '1', text: 'Demo' }]
 * @param allowClear 允许为空（默认：true）
 * @param placeholder 占位符
 * @param required 是否必填
 * @param message 提示信息（如果添加了，所有错误提示为改信息）
 * @param validator 自定义验证函数
 * @param hidden 是否隐藏
 * @param selectable 可以选择的节点（如：leaf只能选择叶子节点，默认可选所有）
 * @param handleDisabled 节点是否可选的控制函数
 * @param fullPath 全路径文本（默认false）
 * @param fullTitleField 装载全路径文本的字段
 */
export function AxSelectTree(props) {
  let { label, value } = props;
  const {
    form,
    data = [],
    mode = '-',
    selectable,
    fullTitleField,
    handleDisabled,
    isLabel = false,
    fullPath = false,
    allowClear = true,
    value: valueFromProps,
    placeholder = `请选择${label}`,
    ...rest
  } = props;

  /** 展示为Label */
  const WrappedComponent = isLabel === true ? AxLabel : TreeSelect;
  /** 当为Label时，将value赋值为text */
  if (isLabel === true) {
    const finder = (d, v) => {
      let r = '';
      for (let i = 0; i < d.length; i++) {
        const o = d[i];
        if (o.id === v) {
          r = o.text;
          break;
        } else if (o.children) r = finder(o.children, v);
        else return (r = '');
      }
      return r;
    };

    value = finder(data, valueFromProps);
  }
  const treeData = axhelper.transToTreeData(data, selectable, handleDisabled);
  if (fullPath === true) loops(treeData);

  const handleSelect = (v) => {
    if (fullPath === true) {
      const fullTitle = getFullPath(v, 'title');
      if (fullTitleField) form.setFieldsValue({
        [fullTitleField]: fullTitle
      });
    }
  }

  return (
    <AxFormItemBase
      form={form}
      mode={mode}
      value={value}
      maxTagCount={1} //最多显示多少个 tag
      allowClear={allowClear}
      placeholder={placeholder}
      style={{ width: '100%' }}
      treeNodeLabelProp="title"
      treeNodeFilterProp="title"
      WrappedComponent={WrappedComponent}
      dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
      treeData={treeData}
      onSelect={handleSelect}
      {...rest}
    />
  );
}
